//
//  YYLPictureView.swift
//  XinlangWeibo
//
//  Created by yangyinglei on 2017/4/7.
//  Copyright © 2017年 yangyinglei. All rights reserved.
//

import UIKit

class YYLPictureView: UICollectionView {
    var picArray:[UIImage] = [UIImage]()
    var picAddCallBack: (()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let itemMargin:CGFloat = 5
        let itemWidth = (ScreenWidth - 2 * homeCellMargin - 2 * itemMargin) / 3
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize.width = itemWidth
        flowLayout.itemSize.height = itemWidth
        
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin

        super.init(frame: frame, collectionViewLayout: flowLayout)

        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = UIColor.white
        //设置代理和数据源
        self.dataSource = self
        self.delegate = self
        self.register(YYLPictureViewCell.self, forCellWithReuseIdentifier: composeItemIdentifier)
        
    }
    //添加图片
    func addImage(image: UIImage) {
    
        if picArray.count >= 9 {
        return
        }
        picArray.append(image)
//        print(image)
        //刷新数据
        reloadData()
    }
    

}

extension YYLPictureView: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if picArray.count == 0 || picArray.count == 9 {
            return (picArray.count)
        }
        return picArray.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: composeItemIdentifier, for: indexPath) as! YYLPictureViewCell
        
        if indexPath.item == picArray.count{
            cell.image = nil
        } else {
            cell.image = picArray[indexPath.item]
            cell.indexPath = indexPath
            //过来的回调删除图片
            cell.deletePicCallBack = {[weak self] (num)->() in
            
            self?.picArray.remove(at: num)
                self?.reloadData()
            }
            
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == self.picArray.count {
        //点击添加图片 回调添加
        picAddCallBack?()
        }
    }
}


class YYLPictureViewCell: UICollectionViewCell {
    //图片
    lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    //cell 的 indexPath
    var indexPath: IndexPath?
    //删除的闭包
    var deletePicCallBack: ((Int)->())?
    //删除按钮
    lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn .addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
        btn.setImage(UIImage(named:"compose_photo_close"), for: .normal)
        btn.sizeToFit()
        return btn 
    }()
    
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
            deleteBtn.isHidden = true
            } else {
                imageView.image = image
                deleteBtn.isHidden = false
            }
        }

    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {

        contentView.addSubview(imageView)
        contentView.addSubview(deleteBtn)
        //  布局
        imageView.snp.makeConstraints({ (make) in
            make.edges.equalTo(self.contentView)
        })
        deleteBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(self.contentView)
        }
        
    }
    
    @objc fileprivate func deleteAction() {
        if let currentIndexPath = indexPath {
        
        deletePicCallBack?(currentIndexPath.item)
        }
    
    }
    
}
